package com.example.websocketrabbitmq.controller;

import com.rabbitmq.client.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 发送测试消息到RabbitMQ
 */
@RestController
public class TestController {
    private final static String QUEUE_NAME = "test_queue";

    @GetMapping("/send")
    public String sendMsg(@RequestParam String msg) {
        // 连接到RabbitMQ
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("guest");

        // 声明队列并发送消息
        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) {
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            //队列和消息均持久化
            AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
                    .deliveryMode(2)
                    .build();
            // Topic交换机测试示例
            channel.exchangeDeclare("test_topic", BuiltinExchangeType.TOPIC);
            channel.queueBind(QUEUE_NAME, "test_topic", "user.*");
            channel.basicPublish("test_topic", "user.create", props, msg.getBytes());

            System.out.println("消息已生产");
        } catch (IOException | TimeoutException e) {
            throw new RuntimeException(e);
        }
        return "消息已发送";
    }
}
